package user

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"mime"
	"net/http"
	"path/filepath"
	"time"
)

const (
	endpoint    = "117.27.231.246:9000"
	accessKey   = "EoSYgm5gu5P9BQdIXzsp"
	secretKey   = "42ILntEI4eirSTOSQJHy1f7C4nK0eeVomK6SBYtS"
	bucketsName = "123"
)

func Upload(c *gin.Context) {
	file, _ := c.FormFile("file")
	client, err := minio.New(endpoint, &minio.Options{
		Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
	})
	if err != nil {
		panic(err)
	}
	open, err := file.Open()
	if err != nil {
		panic(err)
	}
	location, _ := time.LoadLocation("Asia/Shanghai")
	now := time.Now().In(location).Truncate(time.Second)
	strTime := now.Format("20060102150405")
	//if file.Size >= 100*1024 {
	//	c.JSON(http.StatusBadRequest, gin.H{
	//		"code":    500,
	//		"message": "视频过大",
	//	})
	//	return
	//}
	ext := filepath.Ext(file.Filename)
	//if ext != ".mp4" {
	//	c.JSON(http.StatusBadRequest, gin.H{
	//		"code":    500,
	//		"message": "视频类型不正确",
	//	})
	//	return
	//}
	objectName := fmt.Sprintf("%s/%s", strTime, file.Filename)
	contentType := mime.TypeByExtension(ext)
	client.PutObject(c, bucketsName, objectName, open, file.Size, minio.PutObjectOptions{ContentType: mime.TypeByExtension(contentType)})
	url := fmt.Sprintf("http://%s/%s/%s", endpoint, bucketsName, objectName)
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "上传成功",
		"data":    url,
	})
}
